<?php

/* $Id: Edit.class.php 120 2008-05-05 22:34:49Z joshuarudd $ */

class Edit
{

	private $cms;
	private $id;
	private $table;
	private $valid = false;
	private $mode;
	private $body_id;
	private $query_action;
	private $pagetitle;
	
	public	$row_data = null;
	
	function __construct($cms){
		$this->cms = $cms;
		$this->db = $cms->db;
		$this->table = $this->cms->table;
		$this->id = $this->cms->id;
		
		if($this->cms->id){
			$this->mode = "edit";
			$this->pagetitle = $this->cms->label . " - Edit";
			$this->cms->label = $this->pagetitle;
			$this->body_id = "edit";
			$this->query_action = "update";
	
		}else{
			$this->mode = "insert";
			$this->pagetitle = $this->cms->label . " - Add";
			$this->cms->label = $this->pagetitle;
			$this->body_id = "insert";
			$this->query_action = "insert";
		}
	}
	
	function buildPage(){
		
		$history = false;
		if(!$this->cms->session->privs('browse',$this->table)){
			die("You don't have sufficient privileges to view this table");
		}
		
		/*if(isset($_SERVER['HTTP_REFERER'])){
			if($this->cms->refA[0] == 'browse'){
				$this->cms_page_state = preg_replace('[&]','&amp;',$_SERVER['HTTP_REFERER']);
			}else{
				$this->cms_page_state = BLACKBIRD_ROOT . 'browse/' . $this->table;
			}
		}else{
			$this->cms_page_state = BLACKBIRD_ROOT . 'browse/' . $this->table;
		}*/
		
		/*$js = '
		<script type="text/Javascript" src="' . BLACKBIRD_ROOT . ASSETS . 'js/datagrid.js" ></script>
		<script type="text/Javascript" src="' . BLACKBIRD_ROOT . ASSETS . 'js/form.js" ></script>
		<script type="text/Javascript" src="' . BLACKBIRD_ROOT . ASSETS . 'js/dropdown.js" ></script>
		<script type="text/Javascript" src="' . BLACKBIRD_ROOT . ASSETS . 'js/listmanager.js" ></script>';*/
		
		/*$css = '';*/
		
		/*$q_headers = $this->db->queryRow("SELECT * FROM ".BLACKBIRD_TABLE_PREFIX."headers WHERE table_name = '*' AND mode = 'edit'");
		if($q_headers['javascript'] != ''){
			$js .= $q_headers['javascript'];
		}
		if($q_headers['css'] != ''){
			$css .= $q_headers['css'];
		}
		$q_headers = $this->db->queryRow("SELECT * FROM ".BLACKBIRD_TABLE_PREFIX."headers WHERE table_name = '$this->table' AND mode = 'edit'");
		if($q_headers['javascript'] != ''){
			$js .= $q_headers['javascript'];
		}
		if($q_headers['css'] != ''){
			$css .= $q_headers['css'];
		}*/
		
	
		/*
		<ul id="bb_main_sections">
			<li><a href="#" id="bb_toggle_main">Main</a></li>
			<li><a href="#" id="bb_toggle_media">Media</a></li>
			<li><a href="#" id="bb_toggle_sponsors">Sponsors</a></li>
			<li><a href="#" id="bb_toggle_comments">Comments</a></li>
		</ul>
		
			<ul id="edit_nav">
					<li id="tab_main" class="trigger active" ><a href="#" onclick="CMS.showTab(\'main\'); return false;">Details</a></li>';
		
		*/
		
		/*if(isset($this->cms->pathA[3])){
			if ($this->cms->pathA[3] == 'looped'){
				print '<div class="message ok">Record ' . $this->cms->id . ' was saved successfully. <a href="#" onclick="this.up().remove();">Close</a></div>';
			}
		}*/
		
		if($this->mode == "edit"){
			$this->row_data = $this->db->queryRow("SELECT * FROM `$this->table` WHERE id = '$this->id'");
		}
		
		
		//$this->cms->buildHeader($js,$css,' class="edit"',$q_help['help']);
		
		
		
		
		
		
		
		/* BEGIN: TOOLBAR ---------------------------------------------------- */
		
		
		$r = '<div id="bb_toolbar">';
		
		if ($this->mode == 'edit') {
			$q_table = $this->db->queryRow("SELECT * FROM ".BLACKBIRD_TABLE_PREFIX."tables WHERE table_name = '$this->table'");
			$r .= sprintf(
				'<h1>Edit Record%s</h1>',
				$q_table['display_key'] == '' ? '' : ' : '.$this->row_data[$q_table['display_key']]
			);
			// Record metadata
			$r .= '<dl id="bb_record_meta">';
			if (isset($this->row_data['id'])) $r .= sprintf(
				'<dt>Id</dt><dd>%s</dd>',
				$this->row_data['id']
			);
			if (isset($this->row_data['created'])) $r .= sprintf(
				'<dt>Created</dt><dd>%s</dd>',
				$this->row_data['created']
			);
			if (isset($this->row_data['modified'])) $r .= sprintf(
				'<dt>Modified</dt><dd>%s</dd>',
				$this->row_data['modified']
			);
			$r .= '</dl>';
			
		} else {
			$r .= '<h1>New Record</h1>';
		}
		// Record Actions
		$r .= '<div id="bb_record_actions">';
		// Active
		if (isset($this->row_data['active'])) {
			$r .= '<!-- set up change handler to set main_active to this value upon change.. ehh -->';
			$r .= '<select onchange="CMS.setActive(this,\'main\');">';
			if ($this->row_data['active'] == 1) {
				$sel1 = 'selected="selected"';
				$sel0 = '';
			} else {
				$sel0 = 'selected="selected"';
				$sel1 = '';
			}
			$r .= sprintf(
				'<option value="1" %s>Active</option>',
				$sel1
			);
			$r .= sprintf(
				'<option value="0" %s>Inactive</option>',
				$sel0
			);
			$r .= '</select>';
		}
		// Save
		$r .= '<input type="button" value="Save" onclick="CMS.loopBack(\'main\'); return false;" />';
		$r .= sprintf(
			'<input type="button" value="Close" onclick="window.location=\'%s\'; return false;" />',
			$this->cms_page_state
		);
		$r .= '</div>';
		
		$r .= '</div>';
		
		print $r;
		
		/* END: TOOLBAR ------------------------------------------------------ */
		
		
		
		/* BEGIN: RELATED TABLES --------------------------------------------- */
		
		if ($q_related = $this->db->query("SELECT * FROM ".BLACKBIRD_TABLE_PREFIX."relations WHERE table_parent = '$this->table' ORDER BY position")) {
			
			$r = '<ul id="bb_main_sections">';
			
			// Main
			$r .= '<li><a id="bb_toggle_main" class="active" href="#main">Main</a></li>';
			// Related
			foreach ($q_related as $relation) {
				$r .= sprintf(
					'<li><a id="bb_toggle_%s" class="%s" href="#%s">%s</a></li>',
					$relation['table_child'],
					$this->mode == "insert" ? 'dim' : '',
					$relation['table_child'],
					$relation['label']
				);
			}
			// History (NEEDS TO BE MOVED ELSEWHERE... meta?
			/*if($this->mode == 'edit' && $this->table != BLACKBIRD_TABLE_PREFIX.'history'){
				$q_history = $this->db->query("SELECT * FROM ".BLACKBIRD_TABLE_PREFIX."history WHERE table_name = '$this->table' AND record_id = '$this->id'");
				if($q_history && count($q_history) > 0){
					$r .= '<li><a id="tab_history" class="trigger history" href="#">History</a></li>';
					$history = true;
				}
			}*/
			
			$r .= '</ul>';
			
			print $r;
			
		}
		
		/* END: RELATED TABLES ----------------------------------------------- */
		
		
		
		/* BEGIN: MODULE ----------------------------------------------------- */
		
		$r = '<div id="bb_module" class="edit">';
		
		// Check to see if this record exists
		if (is_array($this->row_data) || $this->mode == "insert") {
			
			$valid = true;
			
			// Main table
			$r .= '<div class="section main_' . $this->table . '" id="section_main">';
			ob_start();
			Forms::init(BLACKBIRD_ROOT . "process/remote","form_main","multipart",'post','target="form_target_main" onsubmit="Element.show(\'ajax\');"');
			Forms::hidden("name_space",'main',array('omit_id'=>true));
			Forms::hidden("query_action",$this->query_action,array('omit_id'=>true));
			Forms::hidden("table",$this->cms->table,array('omit_id'=>true));
			Forms::hidden("id",$this->cms->id,array('omit_id'=>true));
			Forms::hidden("loop_back",'');
			Forms::hidden("cms_page_state",$this->cms_page_state);
			require(INCLUDES.'EditRecord.class.php');
			new EditRecord($this->cms,$this->table,$this->id,'main','main');
			Forms::closeTag();
			$r .= ob_get_contents();
			ob_end_clean();
			$r .= '<iframe id="form_target_main" name="form_target_main" class="related_iframe"></iframe>';
			$r .= '</div>';
			
			// Related Tables
			if ($q_related && $this->mode == "edit") {
				
				// AJAX edit record stuff - IS THIS WHERE IT SHOULD STAY???
				$r .= '<div id="ajax" style="display:none;"><div class="container"><div class="icon"></div></div></div>';
				
				$i = 0;
				foreach ($q_related as $relation) {
					
					$name_space = 'related'.$i++;
					$config = (strlen($relation['config']) > 1) ? $this->cms->parseConfig($relation['config']) : '';
					
					$r .= '<div class="section related_' . $relation['table_child'] . '" id="section_' . $relation['table_child'] .'" style="display:none;">';
					
					switch ($relation['display']):
						
						case 'data_grid':
						
							$r .= '<div class="edit_form" style="display:none;">';
							$r .= '<div class="detail"></div>';
							$r .= '</div>';
							
							$r .= '<div class="data_grid_embed">';
							
							ob_start();
							include_once(INCLUDES.'DataGridAjax.class.php');
							$module = new DataGridAjax($this->cms);
							$module->cms = $this->cms;
							$module->table = $relation['table_child'];
							$module->table_parent = $this->cms->table;
							$module->id_parent = $this->cms->id;
							$module->name_space = $name_space;
							$module->config = $config;
							$module->mode = 'related';
							$module->build();
							$r .= ob_get_contents();
							ob_end_clean();
							
							$r .= '</div>';
							
							$r .= '
							<script type="text/javascript">
								<!-- <![CDATA[ 
								var data_grid_' . $name_space . '= new dataGrid(
									{ 	
										mode: \'related\',
										table: \'' . $relation['table_child'] . '\',
										table_parent: \'' . $this->cms->table . '\',
										id_parent: \'' . $this->cms->id . '\',
										name_space: \''. $name_space . '\',
										cms_root: \'' . BLACKBIRD_ROOT . '\',';
										if(isset($config['sql_where'])){
											$r .= 'sql_where: "' . $config['sql_where'] . '"';
										}
										$r .= '
									}
								);
								CMS.broadcaster.addListener(data_grid_'.$name_space.'.listener);
								CMS.addCallback(\'' . $name_space . '\',data_grid_'.$name_space.',"getUpdate");
								// ]]> -->
							</script>';
						
						break;
						
						case 'module':
							
							ob_start();
							$class = $config['module'];
							include_once(INCLUDES.'modules/' . $class . '.class.php');
							$module = new $class($this->cms);
							//$module->cms = $this->cms;
							$module->table = $relation['table_child'];
							$module->name_space = $name_space;
							$module->config = $config;
							$module->build();
							$r .= ob_get_contents();
							ob_end_clean();
							
						break;
						
						case 'plugin':
							
							$class = $config['module'];
							include_once(INCLUDES.'Plugin.interface.php');
							include_once(CUSTOM."php/" . $class . ".class.php");
							$module = new $class();
							$module->cms = $this->cms;
							$module->table = $relation['table_child'];
							$module->name_space = $name_space;
							$module->config = $config;
							$module->build();
							
						break;
					
					endswitch;
					
					$r .= '</div>';
					
				}
				
				
			}
			
			/*if($history){
				
				$name_space = 'history';
				print '<div class="toggle" id="pane_' . $name_space .'" style="display:none;">
				
				<div class="edit_form" style="display:none;">
					<div class="detail"></div>
				</div>';
				
				
				
				print '<div class="data_grid_embed">';
				
				include_once(INCLUDES.'DataGridAjax.class.php');
				$module = new DataGridAjax($this->cms);
				$module->cms = $this->cms;
				$module->table = BLACKBIRD_TABLE_PREFIX.'history';
				$module->name_space = $name_space;
				$module->mode = 'readonly';
				$module->sql = "table_name = '$this->table' AND record_id = '$this->id'";
				$module->build();
				
				print '</div>';
				
				print '</div>';
				
				print '
				<script type="text/javascript">
					<!-- <![CDATA[ 
					var data_grid_' . $name_space . '= new dataGrid(
						{ 	
							table: \''.BLACKBIRD_TABLE_PREFIX.'history\',
							table_parent: \'' . $this->cms->table . '\',
							id_parent: \'' . $this->cms->id . '\',
							name_space: \''. $name_space . '\',
							cms_root: \'' . BLACKBIRD_ROOT . '\'
						}
					);
					// ]]> -->
				</script>';
				
				print '</div>';
			
			}*/
			
		} else {
			
			$r .= sprintf(
				'<p class="error">There was no record %s found in TABLE %s!</p></div>',
				$this->id,
				$this->table
			);
			
		}
		
		$r .= '</div>';
		
		if ($valid === true) {
			$r .= '
			<script type="text/javascript">
				<!-- <![CDATA[ 
				CMS.setProperty("table_parent","' . $this->table . '");
				CMS.setProperty("id_parent","' . $this->id . '");
				
				if($("toggle_help")){
					Event.observe("toggle_help", "click", function(){CMS.toggleHelp(); return false; }, true);
				}';
				
				
				if($this->mode == "edit"){
					$r .= "Event.observe(window, 'load', function(){
						formController_main = new formController('main');
					}, true);";
					
				}
				
				
			$r .= "// ]]> -->
			</script>";
		}
		
		print $r;
		
		/* END: MODULE ------------------------------------------------------- */
		
	}
	
	
	
}